import SceneManager from "../../../LTGame/3d/SceneManager";
import CommonSaveData from "../../../LTGame/Commom/CommonSaveData";
import GlobalUnit from "../../common/GlobalUnit";
import GameHandler, { GameState } from "../../lyf/Game/GameHandler";
import LevelControler from "../../lyf/Game/LevelControler";
import Scene from "../../../LTGame/3d/Scene";

// 3d逻辑
export default class Game3d {
    public static get instance(): Game3d {
        if (this._instance == null) {
            this._instance = new Game3d();
        }
        return this._instance;
    }

    private static _instance: Game3d;

    // 3d 进入游戏
    async enterGame() {
        // 初始化  设置相机  灯光
        let camera = GlobalUnit.camera;
        let light = GlobalUnit.light;
        //camera.active = false;

        Laya.AtlasInfoManager.enable("fileconfig.json", Laya.Handler.create(this, this.onConfigLoaded));
    }
    private onConfigLoaded() {
        Laya.loader.load("ui.json", Laya.Handler.create(this, this.onLoadUI));
    }
    async onLoadUI() {
        Laya.View.uiMap = Laya.loader.getRes("ui.json");
        await this.startLvGame(CommonSaveData.instance.levelId);
    }

    public m_LevelControler: LevelControler;
    private m_CurScene:Scene;
    async startLvGame(lv: number) {
        let scene = this.m_CurScene = SceneManager.instance.getSceneByLv(lv);
        await scene.buildScene();
        // // 取出预制体
        // let shili = scene.prefabs["shili"];

        GameHandler.CurLevelNode = scene.scene as Laya.Sprite3D;
        GameHandler.GameScene = GlobalUnit.s3d;
        let player: Laya.Sprite3D = GameHandler.CurLevelNode.getChildByName("Control").getChildByName("Player") as Laya.Sprite3D;
        let camera: Laya.Camera = GameHandler.CurLevelNode.getChildByName("Control").getChildByName("Camera") as Laya.Camera;
        this.m_LevelControler = new LevelControler(player, camera);
        GameHandler.State = GameState.Being;
    }

    public OnUpdate(){
        if(this.m_LevelControler != null){
            if(GameHandler.State > GameState.Idle && GameHandler.State < GameState.Finished)
            {
                this.m_LevelControler.OnUpdate();
            }
        }
    }

    public GoLevel(lv:number){
        if(this.m_CurScene != null){
            this.m_CurScene.clearScene();
            this.m_CurScene = null;
        }
        this.startLvGame(lv);
    }
}